export default function statement(invoice, plays) {
  const statementData = {};
  statementData.customer = invoice.customer;
  // performance是一个数组 除了原始的playID和audience 新增了play属性
  statementData.performance = invoice.performance.map(enrichPerformance);
  statementData.totalAmount = totalAmount(statementData);
  statementData.totalVolumeCredits = totalVolumeCredits(statementData);
  return renderPlainText(statementData, invoice, plays);
  // 获取performance的副本 不修改传入的参数 数据不可变
  function enrichPerformance(aPerformance) {
    const res = Object.assign({}, aPerformance);
    res.play = playFor(res);
    res.amount = amountFor(res);
    res.volumeCredits = volumeCreditsFor(res);
    return res;
  }
  function playFor(aPerformance) {
    return plays[aPerformance.playID]
  }
  function amountFor(aPerformance) {
    let res = 0
    switch(aPerformance.play.type) {
      case "悲剧":
        res = 40000;
        if (aPerformance.audience > 30) {
          res += 1000 * (aPerformance.audience - 30);
        }
        break;
      case "喜剧": 
      res = 30000;
        if (aPerformance.audience > 20) {
          res += 10000 + 500 * (aPerformance.audience - 20);
        }
        res += 300 * aPerformance.audience
        break
      default:
        throw new Error(`未知的类型: ${play.type}`)
    }
    return res
  }
  function volumeCreditsFor(aPerformance) {
    let res = 0;
    res += Math.max(aPerformance.audience - 30, 0);
    if ("喜剧" === aPerformance.play.type) res += Math.floor(aPerformance.audience / 5);
    return res;
  }
  function totalVolumeCredits(data) {
    let res = 0;
    for (let perf of data.performance) {
      res += perf.volumeCredits;
    }
    return res;
  }
  function totalAmount(data) {
    let res = 0;
    for (let perf of data.performance) {
      res += perf.amount;
    }
    return res;
  }
}
// play 经过 enrichPerformance 函数处理 存入了performance中
function renderPlainText(data, invoice, plays) {
  let res = `【用户${data.customer}的票据单】`;
  for (let perf of data.performance) {
    res += ` ${perf.play.name}: ${usd(perf.amount/100)} (${perf.audience} 座)`;
  }
  res += ` 所欠贷款是 ${usd(data.totalAmount/100)}`;
  res += ` 你赚了 ${data.totalVolumeCredits} 分`;
  return res;

  function usd(aNumber) {
    return new Intl.NumberFormat("en-US", {style: "currency", currency: "USD", minimumFractionDigits: 2}).format(aNumber)
  }
}
